import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import store from '../store';
import pako from '../plugin/pako/index.js'
function toLogin(){
	store.commit("LOGOUT");
	uni.showToast({
		title: '请登录',
		icon: 'none',
		duration: 1000
	});
}
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL, header = HEADER;
	if (!noAuth) {
		//登录过期自动登录
		if (!store.getters.isLogin) {
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}
	if (store.getters.token) header[TOKENNAME] = 'Bearer ' + store.getters.token;
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (res.data && res.data.encode) {
					try
					{
						res.data.data = JSON.parse(pako.decompress(res.data.data));
					}catch(e){
						res.data.data = pako.decompress(decodeURI(res.data.data));
					}
				}
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.status == 200)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 40000].indexOf(res.data.status) !== -1) {
					toLogin();
					reject(res.data);
				} else if (res.data.status == 501) {
					uni.reLaunch({
						url: '/pages/error/index'
					})
					reject(res.data);
				} else
					reject(res.data.message || '网络繁忙，请稍候再试');
					//reject(res.data.message || '系统错误');
			},
			fail: (message) => {
				reject('系统更新，请稍候再试');
				//reject('请求失败');
			}
		})
	});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});
export default request;
